/*
 * Copyright (C) 2013 rdrrlabs gmail com,
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package serv

import (
    "appengine"
    "appengine/datastore"
    "appengine/user"
    "strings"
)


//------------------------------

const kAccessKind = "access"

const (
    GroupAdmin      = "admin"
    GroupView       = "view"
    GroupCreate     = "create"
)

var ValidGroups = map[string] bool {
    GroupAdmin  : true,
    GroupView   : true,
    GroupCreate : true,
}

// Structure stored in AppEngine's datastore
type AccessInfo struct {
    Email   string      `crud:"key"`
    Groups  []string    `datastore:",noindex"`
}

func (u AccessInfo) ToJsonTable() []string {
    // Converts a DataStore entity (the one matching DsStruct) into an array of strings
    // matching the fields expected in the CRUD html data table.
    return []string { u.Email, u.GroupsString() }
}

func (u AccessInfo) GroupsString() string {
    return strings.Join(u.Groups, ", ")
}

func (u *AccessInfo) Is(group string) bool {
    if u.Groups != nil && len(u.Groups) > 0 {
        for _, g := range u.Groups {
            if g == group {
                return true
            }
        }
    }
    return false
}

func (u *AccessInfo) Add(group string) {
    if !u.Is(group) {
        u.Groups = append(u.Groups, group)
    }
}

func FetchAccessInfo(c appengine.Context, u *user.User) (info AccessInfo) {
    if u != nil {
        key := datastore.NewKey(c, kAccessKind, u.Email, 0, nil)
        if err := datastore.Get(c, key, &info); err != nil {
            // Default is to return a user with no valid group.
            return AccessInfo { Email: u.Email }
        }
    }
    return
}


//------------------------------
